from email.quoprimime import body_check

import requests
from bs4 import BeautifulSoup
import time
import json
import re
from datetime import datetime, timedelta, time  # 单独导入需要的类

class BookingSystem:
    def __init__(self, session):
        """
        初始化预订系统
        :param session: 登录后的会话对象
        """
        self.session = requests.session()
        self.base_url = "http://zhcgm.swun.edu.cn"
        self.appointment_url = "http://zhcgm.swun.edu.cn/pages/appointment/appointment?sportTypeId=2&sportTypeName=羽毛球"
        
    def access_booking_page(self):
        """
        访问预订页面
        """
        try:
            print("正在访问羽毛球预订页面...")
            response=self.session.get(self.appointment_url)
            if response.status_code != 200:
                print(f"登录失败，状态码: {response.status_code}")
                return None
            print(f"登录成功，状态码: {response.status_code}")

            print("登录后会话cookies:")
            for cookie in self.session.cookies:
                print(f"  {cookie.name}: {cookie.value}")
            # 保存页面内容以便分析
            with open('booking_page.html', 'w', encoding='utf-8') as f:
                f.write(response.text)
            print("预订页面已保存到 booking_page.html")

            # 检查是否成功访问页面
            if response.status_code == 200:
                print("HTTP请求成功")
                return response
            else:
                print(f"访问预订页面失败，状态码: {response.status_code}")
                return False
                
        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {e}")
            return False
        except Exception as e:
            print(f"访问预订页面时出现错误: {e}")
            return False
    
    def get_fields_data(self,token):
        """
        通过API获取场地数据
        """
        try:
            print("正在获取场地数据...")
            # API接口获取场地信息
            fields_url = "http://zhcgm.swun.edu.cn/onesports-gateway/wechat-c/api/wechat/memberBookController/weChatSessionsList"
            # 修复token传递方式和语法错误
            headers = {
                'Token': token
            }
            # 获取明天的日期
            tomorrow = datetime.now().date() + timedelta(days=1)
            tomorrow_str = tomorrow.strftime("%Y-%m-%d")
            
            body = {
                "fieldId": "1958839442372182016",
                "isIndoor": "",
                "placeTypeId": "",
                "searchDate": tomorrow_str,
                "sportTypeId": "2"
            }
            # 使用正确的session对象和json参数传递body数据
            response = self.session.post(fields_url, headers=headers, json=body, timeout=10)
            print(f"请求状态码: {response.status_code}")
            # print(f"响应内容示例: {response.json()}...")  # 只打印前200个字符
            if response.status_code == 200:
                print("HTTP请求成功")
                return response.text
            else:
                print(f"获取场地数据失败，状态码: {response.status_code}")
                return None  # 返回None而不是False，更符合语义
                
        except Exception as e:
            print(f"获取场地数据时出现错误: {e}")
            return None  # 返回None而不是False，更符合语义

    def check_submit_booking(self, site_result, token):
        """
        提交预订订单
        这个代码好像不是下单的，是检查是否能够下单的代码
        """
        try:
            print("正在准备提交预订...")
            print(f"预订信息:")
            print(f"场地: {site_result['venue_name']}")
            print("时间段:")
            for i, time_slot in enumerate(site_result['time_slots']):
                print(f"  {time_slot}")
            # API接口获取场地信息
            submit_url = "http://zhcgm.swun.edu.cn/onesports-gateway/wechat-c/api/wechat/memberBookController/weChatOrderGeneration"
            # 修复token传递方式和语法错误
            headers = {
                'Token': token
            }
            # 修复参数传递方式
            params = {
                "sessinesId": site_result['ids'][0],
                "sportTypeId": "2"
            }
            # 使用正确的session对象和params参数传递查询参数
            response = self.session.get(submit_url, headers=headers, params=params, timeout=10)
            print(f"请求状态码: {response.status_code}")
            print(f"响应内容示例: {response.json()}...")  # 只打印前200个字符
            if response.status_code == 200:
                print("HTTP请求成功")
                return response
            else:
                print(f"获取场地数据失败，状态码: {response.status_code}")
                return False

        except Exception as e:
            print(f"获取场地数据时出现错误: {e}")
            return False
    def submit_booking(self, site_result, token):
        """
        提交预订订单
        这个代码好像不是下单的，是检查是否能够下单的代码
        """
        try:
            print("正在准备提交预订...")
            print(f"预订信息:")
            print(f"场地: {site_result['venue_name']}")
            print("时间段:")
            for i, time_slot in enumerate(site_result['time_slots']):
                print(f"  {time_slot}")
            # API接口获取场地信息
            submit_url = "http://zhcgm.swun.edu.cn/onesports-gateway/business-service/orders/weChatSessionsReserve"
            # 修复token传递方式和语法错误
            headers = {
                'Token': token,
                'x-usertoken': token
            }
            # 修复参数传递方式
            # 获取明天的日期
            tomorrow = datetime.now().date() + timedelta(days=1)
            # 转换为毫秒级时间戳
            order_use_date = int(datetime.combine(tomorrow, time.min).timestamp() * 1000)
            
            body = {
                "number": 3,
                "orderUseDate": str(order_use_date),
                "requestsList": [
                    {
                        "sessionsId": site_result['ids'][0]
                    },
                    {
                        "sessionsId": site_result['ids'][1]
                    },
                    {
                        "sessionsId": site_result['ids'][2]
                    }
                ],
                "fieldName": "1~6号羽毛球区",
                "fieldId": "1958839442372182016",
                "siteName": site_result['venue_name'],
                "sportTypeName": "羽毛球",
                "sportTypeId": "2"
            }
            # 使用正确的session对象和params参数传递查询参数
            response = self.session.post(submit_url, headers=headers, json=body, timeout=10)
            print(f"请求状态码: {response.status_code}")
            print(f"响应内容示例: {response.json()}...")  # 只打印前200个字符
            if response.status_code == 200:
                print("HTTP请求成功")
                return response
            else:
                print(f"获取场地数据失败，状态码: {response.status_code}")
                return response

        except Exception as e:
            print(f"获取场地数据时出现错误: {e}")
            return False

    
    def get_courts_info(self):
        """
        获取场地信息
        """
        try:
            print("正在获取场地信息...")
            return self.courts

        except Exception as e:
            print(f"获取场地信息时出现错误: {e}")
            return []

    def get_booking_time_slots(self):
        """
        获取可预订的时间段
        """
        try:
            print("正在获取可预订时间段...")
            return self.time_slots

        except Exception as e:
            print(f"获取时间段时出现错误: {e}")
            return []

if __name__ == "__main__":
    # 这里仅作测试使用
    print("羽毛球场地预订模块")
    print("此模块需要与登录模块配合使用")